import { Injectable, Inject } from '@nestjs/common';
import { WECHAT_CLIENT, WECHAT_MODULE_OPTIONS } from './wechat.constants';
import { WechatClient } from './wechat-client.provider';
import { TemplateMessageData, WechatModuleOptions } from './wechat.interface';
import {
  ApiConfig,
  WeChat,
  ApiConfigKit,
  AccessTokenApi,
  TemplateData,
  TemplateApi,
} from 'tnwx';
import { v1 as uuidv1 } from 'uuid';

@Injectable()
export class WechatService {
  constructor(
    @Inject(WECHAT_CLIENT) private readonly redisClient: ApiConfig,
    @Inject(WECHAT_MODULE_OPTIONS)
    private readonly wechatOptions: WechatModuleOptions,
  ) {}

  private getAccessToken() {
    return AccessTokenApi.getAccessToken();
  }

  async getJsSdk(url: string) {
    let appId = ApiConfigKit.getApiConfig.getAppId;
    let timestamp = Date.parse(new Date().toString()) / 1000 + '';
    let noncestr = uuidv1();
    let signature = await WeChat.jssdkSignature(noncestr, timestamp, url);
    return { appId, timestamp, noncestr, signature };
  }
  /**
   * 发送模板消息
   */
  templateMessage(templateMessageData: TemplateMessageData) {
    let templateData = new TemplateData()
      .New()
      .setToUser(templateMessageData.openid)
      .setTemplateId(templateMessageData.id);
    if (templateMessageData.url) {
      templateData = templateData.setTemplateUrl(templateMessageData.url);
    }
    templateMessageData.keywords.forEach((element) => {
      if (!element.color) element.color = '#000000';
      templateData = templateData.add(
        element.key,
        element.value,
        element.color,
      );
    });
    // const templateJson = templateData.build();
    return TemplateApi.send(templateData.build());
  }
}
